package br.com.lucasddaniel.inbuzios.dao;

import java.util.Hashtable;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDiskIOException;
import br.com.lucasddaniel.inbuzios.bean.Device;
import br.com.lucasddaniel.inbuzios.bean.DeviceAdapter;

/**
 * Classe de manipula�ao dos dados para enviar � persistencia.
 * 
 * @author ldsm
 * 
 */
public class DispositivosBTRepositorio {

	public void deletarDevices(Context ctx) throws ExcessaoBanco {
		try {
			BluetoothAdaptadorBanco.abre(ctx);
			BluetoothAdaptadorBanco.deletarDevices(BTEsquemaBanco.TABLE_NAME, "");
		} catch (SQLiteDiskIOException diskIOException) {
			throw new ExcessaoBanco("Memoria insuficiente pra criar o item.", ExcessaoBanco.INSUFFICIENT_MEMORY);
		} finally {
			BluetoothAdaptadorBanco.fecha(true);
		}
	}

	/**
	 * Lista todos os dispositivos da base encontrados e cadastrados pela ultima
	 * vez pelo bluetooth.
	 * 
	 * @param mAdapter
	 * @return
	 * @throws ExcessaoBanco
	 */
	public DeviceAdapter listarDevices(DeviceAdapter mAdapter, Context ctx) throws ExcessaoBanco {
		try {
			BluetoothAdaptadorBanco.abre(ctx);
			Hashtable<String, String> filters = new Hashtable<String, String>();
			Cursor cursorResult = BluetoothAdaptadorBanco.getObjects(BTEsquemaBanco.TABLE_NAME, filters);
			if (cursorResult.moveToFirst()) {
				do {
					Device device = new Device();
					device.setNome(cursorResult.getString(cursorResult.getColumnIndex(BTEsquemaBanco.TABLE_COLUMNS[0].getColumnName())));
					device.setEndereco(cursorResult.getString(cursorResult.getColumnIndex(BTEsquemaBanco.TABLE_COLUMNS[1].getColumnName())));
					device.setPrincipal(cursorResult.getInt(cursorResult.getColumnIndex(BTEsquemaBanco.TABLE_COLUMNS[2].getColumnName())));

					mAdapter.add(device);

				} while (cursorResult.moveToNext());
			}
			cursorResult.close();
		} catch (SQLiteDiskIOException diskIOException) {
			throw new ExcessaoBanco("Memoria insuficiente pra criar o item.", ExcessaoBanco.INSUFFICIENT_MEMORY);
		} finally {
			BluetoothAdaptadorBanco.fecha(true);
		}
		return mAdapter;
	}

	/**
	 * Retorna o device Bluetooth marcado como principal.
	 * 
	 * @return Um Device
	 * @throws ExcessaoBanco
	 */
	public Device buscarDevicePrincipal(Context ctx) throws ExcessaoBanco {
		Device device = new Device();
		try {
			BluetoothAdaptadorBanco.abre(ctx);
			Hashtable<String, String> filters = new Hashtable<String, String>();
			filters.put(BTEsquemaBanco.TABLE_COLUMNS[2].getColumnName(), "" + 1);
			Cursor cursorResult = BluetoothAdaptadorBanco.getObjects(BTEsquemaBanco.TABLE_NAME, filters);
			if (cursorResult.moveToFirst()) {
				device.setNome(cursorResult.getString(cursorResult.getColumnIndex(BTEsquemaBanco.TABLE_COLUMNS[0].getColumnName())));
				device.setEndereco(cursorResult.getString(cursorResult.getColumnIndex(BTEsquemaBanco.TABLE_COLUMNS[1].getColumnName())));
				device.setPrincipal(cursorResult.getInt(cursorResult.getColumnIndex(BTEsquemaBanco.TABLE_COLUMNS[2].getColumnName())));
			}
			cursorResult.close();
			if (device.getEndereco() == null || "".equalsIgnoreCase(device.getEndereco())) {
				throw new ExcessaoBanco("Sem impressora cadastrada");
			}
		} catch (SQLiteDiskIOException diskIOException) {
			throw new ExcessaoBanco("Memoria insuficiente pra criar o item.", ExcessaoBanco.INSUFFICIENT_MEMORY);
		} finally {
			BluetoothAdaptadorBanco.fecha(true);
		}
		return device;
	}

	/**
	 * Cadastra uma lista de dispositivos encontrados pelo bluetooth.
	 * 
	 * @param mAdapter
	 * @throws ExcessaoBanco
	 */
	public void inserirTodosDevices(DeviceAdapter mAdapter, Context ctx) throws ExcessaoBanco {
		int count = mAdapter.getCount();
		for (int i = 0; i < count; i++) {
			Device device = (Device) mAdapter.getItem(i);
			insere(device, ctx);
		}
	}

	/**
	 * Cadastra um device na base.
	 * 
	 * @param device
	 * @throws ExcessaoBanco
	 */
	public void insere(Device device, Context ctx) throws ExcessaoBanco {
		try {
			BluetoothAdaptadorBanco.abre(ctx);
			ContentValues cv = new ContentValues();
			cv.put(BTEsquemaBanco.TABLE_COLUMNS[0].getColumnName(), device.getNome());
			cv.put(BTEsquemaBanco.TABLE_COLUMNS[1].getColumnName(), device.getEndereco());
			cv.put(BTEsquemaBanco.TABLE_COLUMNS[2].getColumnName(), device.getPrincipal());

			BluetoothAdaptadorBanco.insere(BTEsquemaBanco.TABLE_NAME, cv);
		} catch (SQLiteDiskIOException diskIOException) {
			throw new ExcessaoBanco("Memoria insuficiente pra criar o item.", ExcessaoBanco.INSUFFICIENT_MEMORY);
		} finally {
			BluetoothAdaptadorBanco.fecha(true);
		}
	}

	/**
	 * Atualiza um device na base.
	 * 
	 * @param device
	 * @throws ExcessaoBanco
	 */
	public void atualizar(Device device, Context ctx) throws ExcessaoBanco {
		try {
			BluetoothAdaptadorBanco.abre(ctx);
			ContentValues cv = new ContentValues();
			cv.put(BTEsquemaBanco.TABLE_COLUMNS[0].getColumnName(), device.getNome());
			cv.put(BTEsquemaBanco.TABLE_COLUMNS[1].getColumnName(), device.getEndereco());
			cv.put(BTEsquemaBanco.TABLE_COLUMNS[2].getColumnName(), device.getPrincipal());

			BluetoothAdaptadorBanco.atualizar(BTEsquemaBanco.TABLE_NAME, cv, device.getEndereco());
		} catch (SQLiteDiskIOException diskIOException) {
			throw new ExcessaoBanco("Memoria insuficiente pra criar o item.", ExcessaoBanco.INSUFFICIENT_MEMORY);
		} finally {
			BluetoothAdaptadorBanco.fecha(true);
		}
	}
}
